$('#menu').append('<a href="#" id="historique"><div class><img src="http://leekwars.chocakai.org/stats.png">Historique</div></a>');

$.ajax({url: chrome.extension.getURL ("menu_leeks.html")}).done(function (data) {
	var menuLeeks = $(data);

	$('#wrapper').append($(menuLeeks));

	$.ajax({url: "http://leekwars.com/"}).done(function(data) {		
		$(data).find('#tabs a div.leek').each(function(index, data) {
			var leekId = $(data).attr('leek');

			if (leekId != undefined) {
				menuLeeks.find('a:nth-child(' + (index + 1) + ') div').append($(data));
				menuLeeks.find('a:nth-child(' + (index + 1) + ') div .tab').append('<img src="http://static.leekwars.com/image/house.png" />');
				menuLeeks.find('a:nth-child(' + (index + 1) + ')').attr('href', 'http://leekwars.com/leek/' + leekId);
			
				$.ajax({url: "http://leekwars.com/leek/" + leekId}).done(function(data) {
					var index = data.indexOf("Niveau") + 7;
					var lvl = data.substr(index, 100);
					index = lvl.indexOf("<");
					lvl = lvl.substr(0, index);
					
					menuLeeks.find('a[href*="' + leekId + '"] .tab.leek').append('<span class="lvl">' + lvl + '</span>');
				});
			} else {
				menuLeeks.find('a:nth-child(' + (index + 1) + ')').remove();
			}
		});
	});
});

$('#historique').click(function() {
	// Suppression des elements de la page courante
	$('#page').children().remove();
	$('#page').append('<h1>Historique</h1><div id="notifications"></div>');
	
	// Selection de l'onglet 'Historique'
	$('#menu a div').removeClass('menu-active');
	$('#menu #historique div').addClass('menu-active');
	
	// Recuperation des informations
	$('.menu-wrapper-leeks a div[leek]').each(function (index, data) {
		var leekId = $(data).attr('leek');
		
		$.ajax({url: 'http://leekwars.chocakai.org/report/list.php?leekId=' + leekId}).done(function (data) {
			var reports = $.parseJSON(data);

			reports.forEach(function(report, index, reports) {
				$('#page #notifications').append(
					'<a href="http://leekwars.com/report/' + report.fightId + '">'
					+ '<div class="notif">'
					+ (report.teamId != null ? '<img src="http://static.leekwars.com/image/notif/team_fight.png">' : '<img src="http://static.leekwars.com/image/notif/fight.png">')
					+ '<div class="title">Combat de <b>' + report.name + '</b> : ' +  report.fightId + '</div>'
					+ '<span class="message">Voir le rapport</span>'
					+ '</a>'
				);
			});
		});
	});
	
});
